package Server;

import Client.ClientInitClose;
import module.ExamQuestions;
import module.Student;
import module.User;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ServerDao {

    private static List<Student> students = new ArrayList<>();

    public static ObjectInputStream objectInput;
    public static ObjectOutputStream objectOutput;
    public static Student student = new Student();

    //读取学生信息到集合中
    public static void readFile() {
        try {
            objectInput = new ObjectInputStream(new FileInputStream("d:/test/listStudents.txt"));
            Object obj = objectInput.readObject();
            students = (List<Student>) obj;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (null != objectInput) {
                try {
                    objectInput.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //将集合信息写入到文件中覆盖旧数据
    public static void writeFile() {
        try {
            objectOutput = new ObjectOutputStream(new FileOutputStream("d:/test/listStudents.txt"));
            objectOutput.writeObject(students);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != objectOutput) {
                try {
                    objectOutput.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //根据账号修改密码
    public void modifyPassword(ServerInitClose server){

        try {
            int flag = 0;
            String str = (String) server.getIn().readObject();
            String account = str.split(";")[0];
            String password = str.split(";")[1];
            for(Student student : students){
                if(account.equals(student.getAccount())){
                    student.setPassword(password);
                    writeFile();
                    flag = 1;
                }
            }
            if(0 == flag){
                server.getOut().writeObject("fail");
            }else {
                server.getOut().writeObject("success");
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //管理员账号
    public boolean serverManagerCheck(User user) {
               if("admin".equals(user.getAccount()) && "123456".equals(user.getPassword())){
        return true;
             }
           return false;
    }
    //学生账号登录检测
    public boolean serverstudentrCheck(User user) {

        readFile();
        for (Student student : students) {
            ServerDao.student = student;
            if (student.getAccount().equals(user.getAccount()) && student.getPassword().equals(user.getPassword())) {
                return true;
            }
        }
        return false;
    }
}
